﻿using System.Collections.Generic;

namespace DAPNet
{
    public class MedianFilter : IOfflineEffect
    {
        private int parameter;


        public MedianFilter(int parameter)
        {
            this.parameter = parameter;
        }

        public int Parameter
        {
            get 
            { 
                return parameter; 
            }
            set 
            { 
                parameter = value; 
            }
        }

        public void Process(SampleCollection samples)
        {
            SampleCollection clonedSamples = samples.Clone();
            for (int i = 0; i < samples.Count; i++)
            {
                double medianValue = GetMedianValueAt(clonedSamples, i);
                samples[i].SetTrimmedValue(medianValue);
            }
        }
        
        internal double GetMedianValueAt(SampleCollection samples, int index)
        {
            int startIndex = index - parameter;
            int endIndex = index + parameter;
            List<double> neighboringValues = new List<double>();
            for (int i = startIndex; i <= endIndex; i++)
            {
                double value = Sample.BaseValue;
                if (i >= 0 && i < samples.Count)
                {
                    value = samples[i].Value;
                }
                neighboringValues.Add(value);
            }
            neighboringValues.Sort();
            double medianValue = neighboringValues[parameter];
            return medianValue;
        }  
    }
}
